package cn.tedu.config;

import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * MyBatis的配置类
 */

@MapperScan("cn.tedu.dao")
public class MyBatisConfig {
    // 交给SqlSessionFactoryBean的插件对象
    @Bean
    public PageInterceptor getPageInterceptor(){
        PageInterceptor pageInterceptor = new PageInterceptor();
        // 创建属性对象
        Properties properties = new Properties();
        properties.setProperty("value","true");

        pageInterceptor.setProperties(properties);
        return pageInterceptor;
    }

    // 创建Mybatis的核心类
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(
            @Autowired DataSource dataSource,
            @Autowired PageInterceptor pageInterceptor){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        //TODO  添加插件：分页插件
        factoryBean.addPlugins(pageInterceptor);

        return factoryBean;
    }

    // 创建MapperScannerConfigurer对象，进行dao层扫描
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        // 指定扫描的包路径
        configurer.setBasePackage("cn.tedu.dao"); // mybatis的扫描是进行映射扫描

        return configurer;
    }



}
